

#include <rthw.h>
#include <rtthread.h>
#include "board.h"
#include "ev_utils.h"
#include "ev_comm.h"
#include "ev_console.h"
#include "ev_trans.h"
#ifdef RT_USING_FINSH
#include "shell.h"
#endif
#include "ev_version.h"

#define RT_INIT_THREAD_STACK_SIZE       1024
#define RT_INIT_THREAD_PRIORITY         6

ALIGN(8) static rt_uint8_t main_stack[RT_INIT_THREAD_STACK_SIZE];
static struct rt_thread main_thread;

static void init_thread_entry(void *parameter)
{
    (void)parameter;
    hw_delay_init();
    driv_run_led_init();
    ev_console_init(115200);
    rt_show_version();
    rt_kprintf("EV Control Board:   %s\n", driv_get_board());
    rt_kprintf("EV Version:   v%d.%d.%d\n", EV_VERSION_MAJOR, EV_VERSION_MINOR, EV_VERSION_PATCH);
    rt_kprintf("Build Time: %s, %s\n", __DATE__, __TIME__);
    driv_timer_adc_init();
    ev_trans_init(115200);

#ifdef RT_USING_FINSH
    finsh_system_init();
#endif

    ev_packet_t packet;
    while(1) {
        if (!ev_trans_rx(&packet, 500)) {
            ev_comm_process(&packet);
            ev_trans_log("process packet: 0x%04x", packet.cmd);
        }
        driv_run_led_op(-1);
        // rt_thread_mdelay(500);
    }
}

void ev_init(void)
{
    rt_thread_t tid;
    rt_err_t result;

    tid = &main_thread;
    result = rt_thread_init(tid, "main", &init_thread_entry, RT_NULL,
                            main_stack, sizeof(main_stack), RT_INIT_THREAD_PRIORITY, 20);
    RT_ASSERT(result == RT_EOK);

    /* if not define RT_USING_HEAP, using to eliminate the warning */
    (void)result;

    rt_thread_startup(tid);
}

#ifdef RT_USING_FINSH
static long reboot(void)
{
    rt_kprintf("System reboot ...\n");
    driv_cpu_reboot(0);
    return 0;
}
MSH_CMD_EXPORT(reboot, system reboot)
#endif

